#include "SenderDialog.h"
#include "ui_SenderDialog.h"

SenderDialog::SenderDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::SenderDialog)
{
    ui->setupUi(this);
    isStart = false;
    udpsocket = new QUdpSocket(this);
    timer = new QTimer(this);
    connect (timer, SIGNAL(timeout()),
             this, SLOT(sendMessage()));
}

SenderDialog::~SenderDialog()
{
    delete ui;
}

//点击开始广播按钮执行的槽函数
void SenderDialog::on_pushButton_clicked()
{
    if (isStart == false) {
        isStart = true;
        ui->pushButton->setText("停止广播");
        ui->MessageEdit->setEnabled(false);
        ui->portEdit->setEnabled(false);
        //每隔1S钟广播一次
        timer->start(1000);
    } else {
        isStart = false;
        ui->pushButton->setText("开始广播");
        ui->MessageEdit->setEnabled(true);
        ui->portEdit->setEnabled(true);
        timer->stop();
    }
}

void SenderDialog::sendMessage ()
{
    //获取端口号和广播消息
    quint16 port = ui->portEdit->text().toShort();
    QString msg = ui->MessageEdit->text();

    //toLocal8Bit：--》QString--> QByteArray
    udpsocket->writeDatagram(msg.toLocal8Bit(), QHostAddress::Broadcast, port);
    qDebug() << msg;
}











